<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="content-section" th:fragment="content">
    <h2><i class="fas fa-hospital"></i> 病房管理</h2>
    
    <div class="filter-section">
        <select id="wardDeptSelect" class="dept-select" onchange="updateWardList()">
            <option value="">所有科室</option>
        </select>
    </div>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>科室</th>
                <th>楼层</th>
                <th>病房号</th>
                <th>总床位数</th>
                <th>可用床位数</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="wardTableBody">
            <tr>
                <td colspan="6" class="text-center">加载中...</td>
            </tr>
        </tbody>
    </table>

    <!-- 病房详情模态框 -->
    <div id="wardDetailModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>病房详细信息</h3>
            <div id="wardDetailContent">
                <!-- 病床信息将在这里动态加载 -->
            </div>
            <div class="form-buttons">
                <button type="button" class="btn btn-secondary" onclick="hideWardDetailModal()">关闭</button>
            </div>
        </div>
    </div>

    <!-- 护士信息模态框 -->
    <div id="wardNursesModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>负责护士</h3>
            <div id="wardNursesContent">
                <table class="nurse-table">
                    <thead>
                        <tr>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>性别</th>
                            <th>联系电话</th>
                        </tr>
                    </thead>
                    <tbody id="nurseTableBody">
                        <!-- 护士信息将在这里动态加载 -->
                    </tbody>
                </table>
            </div>
            <div class="form-buttons">
                <button type="button" class="btn btn-secondary" onclick="hideWardNursesModal()">关闭</button>
            </div>
        </div>
    </div>

    <!-- 引入样式 -->
    <th:block th:fragment="style">
        <style>
            .filter-section {
                margin-bottom: 20px;
            }

            .dept-select {
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                min-width: 200px;
                font-size: 14px;
            }

            .dept-select:focus {
                outline: none;
                border-color: #4CAF50;
                box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
            }

            .data-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 20px;
            }

            .data-table th,
            .data-table td {
                padding: 12px;
                text-align: left;
                border-bottom: 1px solid #ddd;
            }

            .data-table th {
                background-color: #f5f5f5;
                font-weight: 600;
            }

            .data-table tr:hover {
                background-color: #f9f9f9;
            }

            .btn {
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
                margin-right: 5px;
            }

            .btn-info {
                background-color: #17a2b8;
                color: white;
            }

            .btn-info:hover {
                background-color: #138496;
            }

            .btn-success {
                background-color: #28a745;
                color: white;
            }

            .btn-success:hover {
                background-color: #218838;
            }

            .btn-secondary {
                background-color: #6c757d;
                color: white;
            }

            .btn-secondary:hover {
                background-color: #5a6268;
            }

            .modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
            }

            .modal-content {
                background: white;
                padding: 20px;
                border-radius: 8px;
                width: 600px;
                max-width: 90%;
            }

            .bed-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 15px;
                margin-bottom: 15px;
            }

            .bed-table th,
            .bed-table td {
                padding: 10px;
                border: 1px solid #ddd;
                text-align: left;
            }

            .bed-table th {
                background-color: #f5f5f5;
            }

            .form-buttons {
                text-align: right;
                margin-top: 15px;
            }

            .btn-sm {
                font-size: 0.875rem;
            }

            .mr-2 {
                margin-right: 0.5rem;
            }

            .text-center {
                text-align: center;
            }

            .text-danger {
                color: #dc3545;
            }

            .nurse-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 15px;
                margin-bottom: 15px;
            }

            .nurse-table th,
            .nurse-table td {
                padding: 10px;
                border: 1px solid #ddd;
                text-align: left;
            }

            .nurse-table th {
                background-color: #f5f5f5;
            }
        </style>
    </th:block>

    <!-- 引入脚本 -->
    <th:block th:fragment="script">
        <script th:inline="javascript">
        /*<![CDATA[*/
        // 页面加载完成后初始化数据
        function initializeWardManage() {
            console.log('Initializing ward management...');
            loadDepartments();
            loadWards();
        }

        // 加载科室列表
        function loadDepartments() {
            console.log('Loading departments...');
            var contextPath = /*[[@{/admin/ward-departments}]]*/ '';
            $.ajax({
                url: contextPath,
                method: 'GET',
                dataType: 'json',
                success: function(departments) {
                    console.log('Received departments:', departments);
                    const select = $('#wardDeptSelect');
                    // 清除旧的选项，保留第一个"所有科室"选项
                    select.find('option:not(:first)').remove();
                    
                    // 添加新的科室选项
                    departments.forEach(function(dept) {
                        select.append($('<option>', {
                            value: dept.deptId,
                            text: dept.deptName
                        }));
                    });
                },
                error: function(xhr, status, error) {
                    console.error('加载科室列表失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    if (xhr.status === 401) {
                        window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                    } else {
                        alert('加载科室列表失败: ' + error);
                    }
                }
            });
        }

        // 更新病房列表
        function updateWardList() {
            const deptId = $('#wardDeptSelect').val();
            loadWards(deptId);
        }

        // 加载病房信息
        function loadWards(deptId) {
            var url = /*[[@{/admin/wards}]]*/ '';
            if (deptId) {
                url += '?deptId=' + deptId;
            }
            
            $('#wardTableBody').html('<tr><td colspan="6" class="text-center">加载中...</td></tr>');
            
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function(wards) {
                    console.log('Received wards:', wards);
                    const tbody = $('#wardTableBody');
                    tbody.empty();
                    
                    if (!Array.isArray(wards)) {
                        console.error('Invalid wards data:', wards);
                        tbody.html('<tr><td colspan="6" class="text-center">数据格式不正确</td></tr>');
                        return;
                    }
                    
                    if (wards.length === 0) {
                        tbody.html('<tr><td colspan="6" class="text-center">暂无病房数据</td></tr>');
                        return;
                    }
                    
                    wards.forEach(function(ward) {
                        const row = $('<tr>', {
                            id: 'ward-' + ward.wardId,
                            'data-ward-id': ward.wardId
                        });
                        
                        row.html(`
                            <td>${ward.deptName || '-'}</td>
                            <td>${ward.floorNum || '-'}</td>
                            <td>${ward.wardNum || '-'}</td>
                            <td>${ward.bedCount || 0}</td>
                            <td>${ward.availableBeds || 0}</td>
                            <td>
                                <button class="btn btn-info btn-sm mr-2" onclick="showWardDetail(${ward.wardId})">
                                    <i class="fas fa-eye"></i> 查看
                                </button>
                                <button class="btn btn-success btn-sm mr-2" onclick="confirmAddBed(${ward.wardId}, ${ward.wardNum})">
                                    <i class="fas fa-plus"></i> 增加病床
                                </button>
                                <button class="btn btn-primary btn-sm" onclick="showWardNurses(${ward.wardId})">
                                    <i class="fas fa-user-nurse"></i> 查看护士
                                </button>
                            </td>
                        `);
                        
                        tbody.append(row);
                    });
                },
                error: function(xhr, status, error) {
                    console.error('加载病房列表失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    const tbody = $('#wardTableBody');
                    if (xhr.status === 401) {
                        window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                    } else {
                        tbody.html(`<tr><td colspan="6" class="text-center text-danger">加载病房列表失败: ${error}</td></tr>`);
                    }
                }
            });
        }

        // 添加确认增加病床的函数
        function confirmAddBed(wardId, wardNum) {
            if (confirm('确定要为 ' + wardNum + ' 号病房增加一张病床吗？')) {
                var contextPath = /*[[@{/admin/addBed}]]*/ '';
                $.ajax({
                    url: contextPath,
                    method: 'POST',
                    data: { wardId: wardId },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            alert(response.message);
                            loadWards($('#wardDeptSelect').val()); // 刷新病房列表
                        } else {
                            alert(response.error || '增加病床失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('增加病床失败:', {
                            status: status,
                            error: error,
                            response: xhr.responseText
                        });
                        if (xhr.status === 401) {
                            window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                        } else {
                            alert('增加病床失败: ' + error);
                        }
                    }
                });
            }
        }

        // 显示病房详细信息
        function showWardDetail(wardId) {
            var contextPath = /*[[@{/admin/wardDetail}]]*/ '';
            $.ajax({
                url: contextPath,
                method: 'GET',
                data: { wardId: wardId },
                dataType: 'json',
                success: function(beds) {
                    console.log('Received bed details:', beds);
                    const content = $('#wardDetailContent');
                    content.empty();
                    
                    // 创建床位信息表格
                    const table = $('<table>', { class: 'bed-table' });
                    
                    // 添加表头
                    table.html(`
                        <thead>
                            <tr>
                                <th>床位号</th>
                                <th>状态</th>
                                <th>病人信息</th>
                            </tr>
                        </thead>
                    `);
                    
                    // 创建表体
                    const tbody = $('<tbody>');
                    beds.forEach(function(bed) {
                        const row = $('<tr>');
                        row.html(`
                            <td>${bed.bedNum}</td>
                            <td>${bed.status == 1 ? '入住' : '空闲'}</td>
                            <td>${bed.patientName || '空床'}</td>
                        `);
                        tbody.append(row);
                    });
                    
                    table.append(tbody);
                    content.append(table);
                    $('#wardDetailModal').show();
                },
                error: function(xhr, status, error) {
                    console.error('加载病房详情失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    if (xhr.status === 401) {
                        window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                    } else {
                        alert('加载病房详情失败: ' + error);
                    }
                }
            });
        }

        function hideWardDetailModal() {
            $('#wardDetailModal').hide();
        }

        function showWardNurses(wardId) {
            var contextPath = /*[[@{/admin/ward-nurses}]]*/ '';
            $.ajax({
                url: contextPath,
                method: 'GET',
                data: { wardId: wardId },
                dataType: 'json',
                success: function(nurses) {
                    console.log('Received nurses:', nurses);
                    const tbody = $('#nurseTableBody');
                    tbody.empty();
                    
                    if (!Array.isArray(nurses)) {
                        console.error('Invalid nurses data:', nurses);
                        tbody.html('<tr><td colspan="4" class="text-center">数据格式不正确</td></tr>');
                        return;
                    }
                    
                    if (nurses.length === 0) {
                        tbody.html('<tr><td colspan="4" class="text-center">暂无护士分配到该病房</td></tr>');
                        return;
                    }
                    
                    nurses.forEach(function(nurse) {
                        const row = $('<tr>');
                        row.html(`
                            <td>${nurse.nurseId || '-'}</td>
                            <td>${nurse.nurseName || '-'}</td>
                            <td>${nurse.nurseGender || '-'}</td>
                            <td>${nurse.nursePhone || '-'}</td>
                        `);
                        tbody.append(row);
                    });
                    
                    $('#wardNursesModal').show();
                },
                error: function(xhr, status, error) {
                    console.error('获取护士信息失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    if (xhr.status === 401) {
                        window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                    } else {
                        alert('获取护士信息失败: ' + error);
                    }
                }
            });
        }

        function hideWardNursesModal() {
            $('#wardNursesModal').hide();
        }

        // 在页面加载完成后自动初始化
        $(document).ready(function() {
            console.log('Ward management page loaded');
            if (typeof initializeWardManage === 'function') {
                initializeWardManage();
            } else {
                console.error('initializeWardManage function not found');
            }
        });
        /*]]>*/
        </script>
    </th:block>
</div>
</body>
</html> 